import 'package:get/get.dart';
import 'package:sinosheets/mixin/refresh_mixin.dart';
import 'package:sinosheets/utils/bus_utils.dart';
import 'package:sinosheets/utils/favorite/product_util.dart';

class FavoriteLogic extends GetxController with RefreshMixin {
  // 响应式数据
  final RxList<Map<String, dynamic>> _flashSaleFavorites = <Map<String, dynamic>>[].obs;
  final RxList<Map<String, dynamic>> _normalFavorites = <Map<String, dynamic>>[].obs;
  final RxInt _currentTabIndex = 0.obs;

  // 获取器
  List<Map<String, dynamic>> get flashSaleFavorites => _flashSaleFavorites;
  List<Map<String, dynamic>> get normalFavorites => _normalFavorites;
  int get currentTabIndex => _currentTabIndex.value;

  @override
  void onInit() {
    super.onInit();
    // 延迟加载，确保ProductUtil已初始化
    Future.delayed(Duration(milliseconds: 100), () {
      loadFavoriteProducts();
      onRefresh();
    });
  }

  @override
  void onReady() {
    super.onReady();
    bus.on('favorite_product_changed', (args) {
      onRefresh();
    });
  }

  /// 加载收藏商品数据
  Future<void> loadFavoriteProducts() async {
    try {
      // 检查ProductUtil是否已初始化
      if (!ProductUtil.isInitialized) {
        await ProductUtil.init();
      }

      // 获取收藏的限时抢购商品并转换为Map
      final flashSaleModels = ProductUtil.favoriteFlashSaleProducts;
      final flashSaleList = flashSaleModels.map((model) => _flashSaleModelToMap(model)).toList();
      _flashSaleFavorites.assignAll(flashSaleList);

      // 获取收藏的普通商品并转换为Map
      final normalModels = ProductUtil.favoriteNormalProducts;
      final normalList = normalModels.map((model) => _normalModelToMap(model)).toList();
      _normalFavorites.assignAll(normalList);

      // 更新UI
      update();
    } catch (e) {}
  }

  /// 将FlashSaleProductModel转换为Map
  Map<String, dynamic> _flashSaleModelToMap(dynamic model) {
    return {
      'id': model.productId,
      'inId': model.inId,
      'productName': model.productName,
      'img': model.productImage,
      'price': model.price,
      'crossedPrice': model.crossedPrice,
      'symbol': model.symbol,
      'detailUrl': model.detailUrl,
      'category': model.category,
      'createTime': model.createTime,
      'updateTime': model.updateTime,
    };
  }

  /// 将NormalProductModel转换为Map
  Map<String, dynamic> _normalModelToMap(dynamic model) {
    return {
      'id': model.productId,
      'inId': model.inId,
      'itemName': model.itemName,
      'img': model.productImage,
      'price': model.price,
      'crossedPrice': model.crossedPrice,
      'symbol': model.symbol,
      'detailUrl': model.detailUrl,
      'category': model.category,
      'createTime': model.createTime,
      'updateTime': model.updateTime,
    };
  }

  /// 切换Tab
  void switchTab(int index) {
    _currentTabIndex.value = index;
  }

  /// 刷新数据
  @override
  Future<void> onRefresh() async {
    try {
      await ProductUtil.refreshAllData();
      await loadFavoriteProducts();
    } catch (e) {
      print('FavoriteLogic: 刷新数据失败: $e');
    }
    super.onRefresh();
  }

  /// 获取收藏统计
  Map<String, int> get favoriteStats {
    return {
      'flashSaleCount': _flashSaleFavorites.length,
      'normalCount': _normalFavorites.length,
      'totalCount': _flashSaleFavorites.length + _normalFavorites.length,
    };
  }

  @override
  void onClose() {
    super.onClose();
  }
}
